"use strict";
const path = require("path");
const pathExists = require("path-exists").sync;
const { isObject } = require("@yk-cli-dev/utils");
const npminstall = require("npminstall");
const pkgDir = require("pkg-dir").sync;
const formatPath = require("@yk-cli-dev/format-path");
const fse = require("fs-extra");

class Package {
  constructor(options) {
    if (!options) throw new Error("Package类的参数不能为空");
    if (!isObject(options)) throw new Error("Package类的参数必须为对象");
    //package的目标路径
    this.targetPath = options.targetPath;
    //缓存package的路径
    this.storeDir = options.storeDir;
    //package的name
    this.packageName = options.packageName;
    this.packageVersion = options.packageVersion;
  }
  async prepare() {
    const { getNpmLatestSemverVersion } = await import("@yk-cli-dev/get-npm");
    if (this.storeDir && !pathExists(this.storeDir)) {
      //当缓存目录不存在的时候
      await fse.mkdirpSync(this.storeDir);
    }
    if (!this.packageVersion || this.packageVersion === "latest") {
      this.packageVersion = await getNpmLatestSemverVersion(this.packageName);
    }
  }
  get cacheFilePath() {
    return path.resolve(this.storeDir, `${this.packageName}`);
  }
  //判断当前Package是否存在
  async exists() {
    if (this.storeDir) {
      await this.prepare();
      return pathExists(this.cacheFilePath);
    } else {
      return pathExists(this.targetPath);
    }
  }
  //安装Package
  async install() {
    const { getDefaultRegistry } = await import("@yk-cli-dev/get-npm");
    await this.prepare();
    return npminstall({
      root: this.targetPath,
      registry: getDefaultRegistry(),
      storeDir: this.storeDir,
      pkgs: [{ name: this.packageName, version: this.packageVersion }],
    });
  }
  //更新Package
  async update() {
    const { getNpmLatestSemverVersion, getDefaultRegistry } = await import(
      "@yk-cli-dev/get-npm"
    );
    await this.prepare();
    //1. 获取最新的npm模块的版本号
    const latestPackageVersion = await getNpmLatestSemverVersion(
      this.packageName
    );
    // 2.查询最新版本对应的路径是否存在
    if (pathExists(this.cacheFilePath)) {
      const dir = pkgDir(this.cacheFilePath);
      if (dir) {
        const pkgFile = require(path.resolve(dir, "package.json"));
        if (pkgFile.version === latestPackageVersion) {
          return;
        }
        // 3. 如果不存在，则直接安装最新版本
        npminstall({
          root: this.targetPath,
          registry: getDefaultRegistry(),
          storeDir: this.storeDir,
          pkgs: [
            { name: this.packageName, version: this.latestPackageVersion },
          ],
        });
        this.packageVersion = latestPackageVersion;
      }
    }
  }
  //获取文件的入口路径
  getRootFilePath() {
    function _getRootFile(targetPath) {
      //1. 获取package.json所在目录 ==>pkg-dir(库)
      console.log(targetPath,'targetPath==mm');
      const dir = pkgDir(targetPath);
      if (dir) {
        //2. 读取 package.json==> require()
        const pkgFile = require(path.resolve(dir, "package.json"));
        //3. 寻找main/lib ==>path
        if (pkgFile?.main) {
          //4. 路径的兼容（macOS/Windows）
          return formatPath(path.resolve(dir, pkgFile.main)); //入口文件的绝对路径
        }
        formatPath();
      }
      return null;
    }
    console.log(this.cacheFilePath,'mmmmmmmmmmmmmthis.targetPath1');
    console.log(this.storeDir,'mmmmmmmmmmmmmthis.targetPath2');
    console.log(this.targetPath,'mmmmmmmmmmmmmthis.targetPath3');
    if (this.storeDir) {
      //使用缓存，自定义目录
      return _getRootFile(this.cacheFilePath);
    } else {
      return _getRootFile(this.targetPath);
    }
  }
}

module.exports = Package;
